// const BASE_API = "http://192.168.10.162:8080"
const BASE_API = "https://fb.macro-cloud.com/api"
// const BASE_API = "/api"


import { getAuthorization, deleteAuthorization, hasAuth, trimParams } from "@/common/constant.js"
import { onDeleteUserinfoData, onDeleteRoleIdData, onDeleteRolesData } from "@/common/userinfo.js"

function apiAxios(method, url, params, headers = {}, otherOptions = {}) {
	if (hasAuth()) {
		headers['Authorization'] = 'Bearer ' + getAuthorization();
	}
	if (!headers['Content-Type']) {
		headers['Content-Type'] = 'application/json;'
	}

	return new Promise((resolve, reject) => {
		uni.showLoading({ title: '请求中...'});
		uni.request({
			url: BASE_API + url,
			method,
			data: trimParams(params),
			...otherOptions,
			header: headers,
			success: res => {
				let { data, code, msg } = res.data
				uni.hideLoading()
				
				if (code === 200) {
					resolve(res.data);
					return
				}
				
				if (code === 401) {
					uni.showToast({ title: msg || '登录状态已过期，请重新授权！', icon: 'none' })
					deleteAuthorization()
					onDeleteUserinfoData()
					onDeleteRoleIdData()
					onDeleteRolesData()
					uni.reLaunch({ url: '/pages/login/login' })
				}
				if (code === 403) {
					uni.showToast({ title: msg || '暂无访问权限，请联系管理员！', icon: 'none' })
				}
				
				if (code === 500) {
					uni.showToast({ title:  msg || '服务异常！', icon: 'none' })
				}
				reject(res);
			},
			fail: (err) => {
				uni.hideLoading()
				reject(err.message)
			}
		});
	});
}
export default {
	get: function(url, params) {
		return apiAxios('GET', url, params)
	},
	post: function(url, params, headers = {}, otherOptions = {}) {
		return apiAxios('POST', url, params, headers, otherOptions)
	},
	put: function(url, params) {
		return apiAxios('PUT', url, params)
	},
	delete: function(url, params) {
		return apiAxios('DELETE', url, params)
	}
}